package com.qiguliuxing.dts.admin.service;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.github.binarywang.wxpay.bean.request.WxPayRefundRequest;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.qiguliuxing.dts.admin.dao.OrderVo;
import com.qiguliuxing.dts.admin.dao.RefundOrderVo;
import com.qiguliuxing.dts.admin.util.AdminResponseUtil;
import com.qiguliuxing.dts.admin.util.DtsBrandVo;
import com.qiguliuxing.dts.core.express.ExpressService;
import com.qiguliuxing.dts.core.notify.NotifyService;
import com.qiguliuxing.dts.core.notify.NotifyType;
import com.qiguliuxing.dts.core.type.RefundTypeEnum;
import com.qiguliuxing.dts.core.util.JacksonUtil;
import com.qiguliuxing.dts.core.util.ResponseUtil;
import com.qiguliuxing.dts.db.domain.*;
import com.qiguliuxing.dts.db.service.*;
import com.qiguliuxing.dts.db.util.OrderUtil;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;

import static com.qiguliuxing.dts.admin.util.AdminResponseCode.ORDER_CONFIRM_NOT_ALLOWED;

@Service
public class AdminOrderService {
    private static final Logger logger = LoggerFactory.getLogger(AdminOrderService.class);

    @Autowired
    private DtsOrderGoodsService orderGoodsService;
    @Autowired
    private DtsBrandService dtsBrandService;
    @Autowired
    private DtsOrderService orderService;
    @Autowired
    private DtsGoodsProductService productService;
    @Autowired
    private DtsUserService userService;
    @Autowired
    private DtsCommentService commentService;
    @Autowired
    private ExpressService expressService;
    @Autowired
    private DtsRefundService refundService;
    /*
     * @Autowired private WxPayService wxPayService;
     */
    @Autowired
    private NotifyService notifyService;

    @Autowired
    private AdminDataAuthService adminDataAuthService;

    @Autowired
    private DtsGrouponService grouponService;

    public Object list(Integer userId, String orderSn, String fetchCode, List<Short> orderStatusArray, Integer page, Integer limit,
                       String sort, String order) {

        // 需要区分数据权限，如果属于品牌商管理员，则需要获取当前用户管理品牌店铺
        List<Integer> brandIds = null;
        if (adminDataAuthService.isBrandManager()) {
            brandIds = adminDataAuthService.getBrandIds();
            logger.info("运营商管理角色操作，需控制数据权限，brandIds:{}", JSONObject.toJSONString(brandIds));

            if (brandIds == null || brandIds.size() == 0) {//如果尚未管理任何入驻店铺，则返回空数据
                Map<String, Object> data = new HashMap<>();
                data.put("total", 0L);
                data.put("items", null);

                logger.info("【请求结束】商场管理->订单管理->查询,响应结果:{}", JSONObject.toJSONString(data));
                return ResponseUtil.ok(data);
            }
        }
        List<DtsOrder> orderList = null;
        long total = 0L;
        if (brandIds == null || brandIds.size() == 0) {
            orderList = orderService.querySelective(userId, orderSn, fetchCode, orderStatusArray, page, limit, sort, order);
            total = PageInfo.of(orderList).getTotal();
        } else {
            orderList = orderService.queryBrandSelective(brandIds, userId, orderSn, fetchCode, orderStatusArray, page, limit, sort, order);
            total = PageInfo.of(orderList).getTotal();
        }

        //验证订单是否可以存在退货子订单和团购类型订单（只有已购买等到发货的商品才验证是否团购中)
        List<OrderVo> orderVoList = null;
        if (orderList != null && orderList.size() > 0) {
            orderVoList = new ArrayList<OrderVo>();
            for (DtsOrder dtsOrder : orderList) {
                OrderVo orderVo = new OrderVo();
                BeanUtils.copyProperties(dtsOrder, orderVo);
                orderVo.setHasRefund(orderService.hasRefundByAudit(dtsOrder.getId()));
                /**
                 * 已付款待发货的订单需要验证是否为团购订单，如果是团购订单还需要确认是团购已达到人数要求
                 */
                if (dtsOrder.getOrderStatus().intValue() == OrderUtil.STATUS_PAY.intValue()) {
                    if (grouponService.isGrouponIng(dtsOrder.getId())) {
                        orderVo.setOrderStatus(OrderUtil.STATUS_GROUPON_ING);
                    }
                }
                /**
                 * 自提订单查询是否有带上自提码进行查询，如果有则显示自提码
                 * 如果是店铺管理员发起查询，且条件未带上取货码，则不出现提货码在订单数据中
                 * fetchCode
                 */
                if (adminDataAuthService.isBrandManager() && StringUtils.isEmpty(fetchCode)) {
                    logger.info("运营商管理角色操作，需控制数据权限，这里不给前端反馈取货码");
                    orderVo.setFetchCode(null);//店铺管理员去掉取货码信息
                }

                orderVoList.add(orderVo);
            }
        }

        Map<String, Object> data = new HashMap<>();
        data.put("total", total);
        data.put("items", orderVoList);

        logger.info("【请求结束】商场管理->订单管理->查询,响应结果:{}", JSONObject.toJSONString(data));
        return ResponseUtil.ok(data);
    }

    public Object finishOrder(String orderIdList) {
        if (org.apache.commons.lang3.StringUtils.isEmpty(orderIdList)) {
            return ResponseUtil.fail(500, "必须有订单ID");
        }
        String[] arr = orderIdList.split(",");
        if (arr.length == 0) {
            return ResponseUtil.fail(500, "必须有订单ID");
        }
        orderService.finishOrder(Lists.newArrayList(arr));
        return ResponseUtil.ok();
    }

    public Object brandList() {
        List<Integer> brandIds = null;
        //仅仅只是品牌管理员且不属于超级管理员
        List<DtsBrand> brandList = null;
        List<DtsBrandVo> voList = Lists.newArrayList();
        if (adminDataAuthService.isBrandManager()) {
            brandIds = adminDataAuthService.getBrandIds();
            logger.info("【对账明细】运营商管理角色操作，需控制数据权限，brandIds:{}", JSONObject.toJSONString(brandIds));
            if (brandIds == null || brandIds.size() == 0) {
                return null;
            }
            //商户
            brandList = dtsBrandService.queryByBrandIds(brandIds);
        }
        //管理员
        if (adminDataAuthService.isAdminManager()) {
            brandList = dtsBrandService.all();
        }
        if (CollectionUtils.isNotEmpty(brandList)) {
            brandList.stream().forEach(dtsBrand -> {
                DtsBrandVo vo = new DtsBrandVo();
                BeanUtils.copyProperties(dtsBrand, vo);
                voList.add(vo);
            });
        }

        Map<String, Object> data = new HashMap<>();
        data.put("brandList", voList);

        return ResponseUtil.ok(data);
    }

    public Object verifyList(String startTime, String endTime, Integer userId, Integer brandId, Integer settlementFlag, String orderSn, String fetchCode, List<Short> orderStatusArray, Integer page, Integer limit,
                             String sort, String order) {

        // 需要区分数据权限，如果属于品牌商管理员，则需要获取当前用户管理品牌店铺
        List<Integer> brandIds = null;
        if (adminDataAuthService.isBrandManager()) {
            brandIds = adminDataAuthService.getBrandIds();
            logger.info("【对账明细】运营商管理角色操作，需控制数据权限，brandIds:{}", JSONObject.toJSONString(brandIds));
            if (brandIds == null || brandIds.size() == 0) {//如果尚未管理任何入驻店铺，则返回空数据
                Map<String, Object> data = new HashMap<>();
                data.put("total", 0L);
                data.put("items", null);
                logger.info("【对账明细】商场管理->订单管理->查询,响应结果:{}", JSONObject.toJSONString(data));
                return null;
            }
        }
        List<DtsOrder> orderList = null;
        long total = 0L;
        if (Objects.nonNull(brandId)) {
            brandIds = Lists.newArrayList(brandId);
        }
        if (brandIds == null || brandIds.size() == 0) {
            orderList = orderService.querySelectiveVerify(startTime, endTime, userId, settlementFlag, orderSn, fetchCode, orderStatusArray, page, limit, sort, order);
            total = PageInfo.of(orderList).getTotal();
        } else {
            orderList = orderService.queryBrandSelectiveVerify(startTime, endTime, brandIds, userId, settlementFlag, orderSn, fetchCode, orderStatusArray, page, limit, sort, order);
            total = PageInfo.of(orderList).getTotal();
        }

        //验证订单是否可以存在退货子订单和团购类型订单（只有已购买等到发货的商品才验证是否团购中)
        List<OrderVo> orderVoList = Lists.newArrayList();
        if (orderList != null && orderList.size() > 0) {
            orderList.stream().forEach(dto -> {
                OrderVo orderVo = new OrderVo();
                BeanUtils.copyProperties(dto, orderVo);
                orderVo.setHasRefund(false);
                orderVo.setHasSettlement(false);
                if ((orderVo.getOrderStatus() == 401 || orderVo.getOrderStatus() == 402) && orderVo.getSettlementFlag() == 1) {
                    orderVo.setHasSettlement(true);
                }
                orderVoList.add(orderVo);
            });
        }

        Map<String, Object> data = new HashMap<>();
        data.put("total", total);
        data.put("items", orderVoList);

        logger.info("【对账明细】商场管理->订单管理->查询,响应结果:{}", JSONObject.toJSONString(data));
        return ResponseUtil.ok(data);
    }

    public Object detail(Integer id) {
        DtsOrder order = orderService.findById(id);
        if (adminDataAuthService.isBrandManager()) {
            logger.info("运营商管理角色操作，需控制数据权限，这里不给前端反馈取货码");
            order.setFetchCode(null);//店铺管理员去掉取货码信息
        }
        List<DtsOrderGoods> orderGoods = orderGoodsService.queryByOid(id);
        UserVo user = userService.findUserVoById(order.getUserId());
        Map<String, Object> data = new HashMap<>();

        /**
         * 已付款待发货的订单需要验证是否为团购订单，如果是团购订单还需要确认团购已达到人数要求
         */
        if (order.getOrderStatus().intValue() == OrderUtil.STATUS_PAY.intValue()) {
            if (grouponService.isGrouponIng(order.getId())) {
                order.setOrderStatus(OrderUtil.STATUS_GROUPON_ING);
            }
        }
        data.put("order", order);
        data.put("orderGoods", orderGoods);
        data.put("user", user);

        logger.info("【请求结束】商场管理->订单管理->详情,响应结果:{}", JSONObject.toJSONString(data));
        return ResponseUtil.ok(data);
    }

    /**
     * 订单退款
     * <p>
     * 1. 检测当前订单是否能够退款; 2. 微信退款操作; 3. 设置订单退款确认状态； 4. 订单商品库存回库。
     * <p>
     * TODO 虽然接入了微信退款API，但是从安全角度考虑，建议开发者删除这里微信退款代码，采用以下两步走步骤： 1.
     * 管理员登录微信官方支付平台点击退款操作进行退款 2. 管理员登录Dts管理后台点击退款操作进行订单状态修改和商品库存回库
     *
     * @param body 订单信息，{ orderId：xxx }
     * @return 订单退款操作结果
     */
    @Transactional
    public Object refund(String body) {
        Integer refundID = JacksonUtil.parseInteger(body, "id");
        Integer orderId = JacksonUtil.parseInteger(body, "orderId");
        String refundAmount = JacksonUtil.parseString(body, "refundAmount");
        String approveMsg = JacksonUtil.parseString(body, "approveMsg");
        Byte approveStatus = JacksonUtil.parseByte(body, "approveStatus");
        String refundReason = JacksonUtil.parseString(body, "refundReason");
        if (refundID == null) {
            return ResponseUtil.badArgument();
        }
        if (StringUtils.isEmpty(refundAmount)) {
            return ResponseUtil.badArgument();
        }
        if (approveStatus == null || approveMsg == null) {
            return ResponseUtil.badArgument();
        }
        DtsOrder order = orderService.findById(orderId);
        if (order == null) {
            return ResponseUtil.badArgument();
        }

		/*if (order.getActualPrice().compareTo(new BigDecimal(refundMoney)) != 0) {
			return ResponseUtil.badArgumentValue();
		}

		// 如果订单不是退款状态，则不能退款
		if (!order.getOrderStatus().equals(OrderUtil.STATUS_REFUND)) {
			logger.info("商场管理->订单管理->订单退款失败:{}", ORDER_REFUND_FAILED.desc());
			return AdminResponseUtil.fail(ORDER_REFUND_FAILED);
		}*/

        // 退款通过，则做微信退款
        if (approveStatus.intValue() == RefundTypeEnum.APPROVE_FINISH.getStatus().intValue()) {
            WxPayRefundRequest wxPayRefundRequest = new WxPayRefundRequest();
            wxPayRefundRequest.setOutTradeNo(order.getOrderSn());
            wxPayRefundRequest.setOutRefundNo("refund_" + order.getOrderSn());
            // 元转成分
            Integer totalFee = order.getActualPrice().multiply(new BigDecimal(100)).intValue();
            wxPayRefundRequest.setTotalFee(totalFee);
            Integer refundFree = new BigDecimal(refundAmount).multiply(new BigDecimal(100)).intValue();
            wxPayRefundRequest.setRefundFee(refundFree);

            /**
             * 为了账号安全，暂时屏蔽api退款 WxPayRefundResult wxPayRefundResult = null; try {
             * wxPayRefundResult = wxPayService.refund(wxPayRefundRequest); } catch
             * (WxPayException e) { e.printStackTrace(); return
             * ResponseUtil.fail(ORDER_REFUND_FAILED, "订单退款失败"); } if
             * (!wxPayRefundResult.getReturnCode().equals("SUCCESS")) { logger.warn("refund
             * fail: " + wxPayRefundResult.getReturnMsg()); return
             * ResponseUtil.fail(ORDER_REFUND_FAILED, "订单退款失败"); } if
             * (!wxPayRefundResult.getResultCode().equals("SUCCESS")) { logger.warn("refund
             * fail: " + wxPayRefundResult.getReturnMsg()); return
             * ResponseUtil.fail(ORDER_REFUND_FAILED, "订单退款失败"); }
             */
        }

        //退货跟踪表数据状态调整为已退款或者等待退款
        refundService.approveRefund(refundID, approveStatus, approveMsg, refundAmount);

        // 退款通过，则商品货品数量增加
        if (approveStatus.intValue() == RefundTypeEnum.APPROVE_FINISH.getStatus().intValue()) {
            List<DtsOrderGoods> orderGoodsList = refundService.queryOrderGoodsByRefundId(refundID);
            for (DtsOrderGoods orderGoods : orderGoodsList) {
                Integer productId = orderGoods.getProductId();
                Short number = orderGoods.getNumber();
                if (productService.addStock(productId, number) == 0) {
                    logger.info("商场管理->订单管理->订单退款失败:{}", "商品货品库存增加失败");
                    throw new RuntimeException("商品货品库存增加失败");
                }
            }
        }

        //等待退款
        if (order.getOrderStatus().intValue() == OrderUtil.STATUS_REFUND.intValue()
                && approveStatus == RefundTypeEnum.APPROVE_OK.getStatus()) {//如果订单是已退款中，表示所有商品都已经退款中，则如果所有的退款子订单都已经完成退款，需调整状态
            Long unFinishCnt = refundService.unFinishCntRefundByOrderId(orderId, RefundTypeEnum.APPROVE_OK.getStatus());
            if (unFinishCnt == 0) { //没完成的退款子订单数已经为 0 即所有子退款订单已经完成，设置订单取消状态
                order.setOrderStatus(OrderUtil.STATUS_REFUND_WITE);
                if (orderService.updateWithOptimisticLocker(order) == 0) {
                    logger.info("商场管理->订单管理->订单退款失败:{}", "更新数据已失效");
                    throw new RuntimeException("更新数据已失效");
                }
            }

        }

        //退款完成
        if (order.getOrderStatus().intValue() == OrderUtil.STATUS_REFUND_WITE.intValue()
                && approveStatus == RefundTypeEnum.APPROVE_FINISH.getStatus()) {
            Long unFinishCnt = refundService.unFinishCntRefundByOrderId(orderId, RefundTypeEnum.APPROVE_FINISH.getStatus());
            if (unFinishCnt == 0) { //没完成的退款子订单数已经为 0 即所有子退款订单已经完成，设置订单取消状态
                order.setOrderStatus(OrderUtil.STATUS_REFUND_CONFIRM);
                if (orderService.updateWithOptimisticLocker(order) == 0) {
                    logger.info("商场管理->订单管理->订单退款失败:{}", "更新数据已失效");
                    throw new RuntimeException("更新数据已失效");
                }
            }
        }

        // TODO 发送邮件和短信通知，这里采用异步发送
        // 退款成功通知用户, 例如“您申请的订单退款 [ 单号:{1} ] 已成功，请耐心等待到账。”
        // 注意订单号只发后6位
        //TODO 微信通知
        if (approveStatus.intValue() == RefundTypeEnum.APPROVE_FINISH.getStatus().intValue()) {
            List<DtsUser> list = userService.queryByMobile(order.getMobile());
            if (CollectionUtils.isNotEmpty(list) && org.apache.commons.lang3.StringUtils.isNotBlank(list.get(0).getWeixinOpenid())) {
                notifyService.notifyWxTemplate(list.get(0).getWeixinOpenid(), NotifyType.REFUND, new String[]{order.getOrderSn(), order.getActualPrice().toString(), "微信钱包", refundReason});
            } else {
                logger.error("【微信通知】申请退款，没有找到用户,order:{}", order);
            }
        }
        logger.info("【请求结束】商场管理->订单管理->订单退款,响应结果:{}", "成功!");
        return ResponseUtil.ok();
    }

    /**
     * 发货 1. 检测当前订单是否能够发货 2. 设置订单发货状态
     *
     * @param body 订单信息，{ orderId：xxx, shipSn: xxx, shipChannel: xxx }
     * @return 订单操作结果 成功则 { errno: 0, errmsg: '成功' } 失败则 { errno: XXX, errmsg: XXX }
     */
    public Object ship(String body) {
        Integer orderId = JacksonUtil.parseInteger(body, "orderId");
        String shipSn = JacksonUtil.parseString(body, "shipSn");
        String shipChannel = JacksonUtil.parseString(body, "shipChannel");
        if (orderId == null || shipSn == null || shipChannel == null) {
            return ResponseUtil.badArgument();
        }

        DtsOrder order = orderService.findById(orderId);
        if (order == null) {
            return ResponseUtil.badArgument();
        }

        // 如果订单不是已付款状态，则不能发货
        if (!order.getOrderStatus().equals(OrderUtil.STATUS_PAY)) {
            logger.info("商场管理->订单管理->订单发货失败:{}", ORDER_CONFIRM_NOT_ALLOWED.desc());
            return AdminResponseUtil.fail(ORDER_CONFIRM_NOT_ALLOWED);
        }

        order.setOrderStatus(OrderUtil.STATUS_SHIP);
        order.setShipSn(shipSn);
        order.setShipChannel(shipChannel);
        order.setShipTime(LocalDateTime.now());
        if (orderService.updateWithOptimisticLocker(order) == 0) {
            logger.info("商场管理->订单管理->订单发货失败:{}", "更新数据失败!");
            return ResponseUtil.updatedDateExpired();
        }

        List<DtsOrderGoods> orderGoods = orderGoodsService.queryByOid(order.getId());
        String productName = "";
        if (CollectionUtils.isNotEmpty(orderGoods)) {
            productName = orderGoods.get(0).getGoodsName();
        }
        // TODO 发送邮件和短信通知，这里采用异步发送
        // 发货会发送通知短信给用户: *
        // "您的订单已经发货，快递公司 {1}，快递单 {2} ，请注意查收"
        //notifyService.notifySmsTemplate(order.getMobile(), NotifyType.SHIP, new String[] { shipChannel, shipSn });
        //TODO 微信通知
        List<DtsUser> userList = userService.queryByMobile(order.getMobile());
        if (CollectionUtils.isNotEmpty(userList) && userList.size() == 1 && Objects.nonNull(userList.get(0).getWeixinOpenid())) {
            notifyService.notifyWxTemplate(userList.get(0).getWeixinOpenid(), NotifyType.SHIP, new String[]{order.getOrderSn(), productName, order.getShipChannel(), order.getShipSn(), DateUtil.formatChineseDate(new Date(), false)});
        } else {
            logger.error("【微信通知】订单发货，没有找到用户openId，order:{}", order);
        }

        logger.info("【请求结束】商场管理->订单管理->订单发货,响应结果:{}", "成功!");
        return ResponseUtil.ok();
    }

    public static void main(String[] args) {
        String date = DateUtil.formatChineseDate(new Date(), false);
        System.out.println(date);
    }

    /**
     * 回复订单商品
     */
    public Object reply(Integer adminId, String body) {
        Integer commentId = JacksonUtil.parseInteger(body, "commentId");
        if (commentId == null || commentId == 0) {
            return ResponseUtil.badArgument();
        }
		/*if (commentService.findById(commentId) != null) {
			logger.info("商场管理->订单管理->订单商品回复:{}", ORDER_REPLY_EXIST.desc());
			return AdminResponseUtil.fail(ORDER_REPLY_EXIST);
		}*/
        DtsComment oldComment = commentService.findById(commentId);
        String content = JacksonUtil.parseString(body, "content");
        if (StringUtils.isEmpty(content)) {
            return ResponseUtil.badArgument();
        }
        // 创建评价回复
        DtsComment comment = new DtsComment();
        comment.setType(oldComment.getType());
        comment.setValueId(oldComment.getValueId());
        comment.setContent(content);
        comment.setUserId(null);
        comment.setHasPicture(false); // 评价回复没有用
        comment.setPicUrls(new String[]{}); // 评价回复没有用
        comment.setStar((short) 0); // 评价回复没有用
        comment.setAddTime(LocalDateTime.now());//创建时间
        comment.setUpdateTime(LocalDateTime.now());//更新时间
        comment.setRepliedToId(commentId);//回复的评论
        comment.setIsRoot(false);//非根评论
        comment.setRootId(oldComment.getRootId() != null && oldComment.getRootId().intValue() > 0 ? oldComment.getRootId() : oldComment.getId());
        comment.setAdminId(adminId);
        commentService.save(comment);

        logger.info("【请求结束】商场管理->订单管理->订单商品回复,响应结果:{}", "成功!");
        return ResponseUtil.ok();
    }

    /**
     * 快递公司列表
     *
     * @return
     */
    public Object listShipChannel() {
        List<Map<String, String>> vendorMaps = expressService.getAllVendor();
        List<Map<String, Object>> shipChannelList = new ArrayList<Map<String, Object>>(vendorMaps == null ? 0 : vendorMaps.size());
        for (Map<String, String> map : vendorMaps) {
            Map<String, Object> b = new HashMap<>(2);
            b.put("value", map.get("code"));
            b.put("label", map.get("name"));
            shipChannelList.add(b);
        }

        Map<String, Object> data = new HashMap<>();
        data.put("shipChannelList", shipChannelList);
        logger.info("获取已配置的快递公司总数：{}", shipChannelList.size());
        return ResponseUtil.ok(data);
    }

    /**
     * 提货确认（店铺管理员或用户均可对自提订单进行提货确认）
     *
     * @param body
     * @return
     */
    public Object confirm(String body) {
        Integer orderId = JacksonUtil.parseInteger(body, "orderId");
        if (orderId == null) {
            return ResponseUtil.badArgument();
        }
        DtsOrder order = orderService.findById(orderId);
        if (order == null) {
            return ResponseUtil.badArgument();
        }
        // 设置订单确认状态
        order.setOrderStatus(OrderUtil.STATUS_CONFIRM);
        //如果是自提订单，确认收货时需设置发货时间为自提确认时间
        if (order.getFreightType().intValue() == 1) {
            order.setShipTime(LocalDateTime.now());
        }
        order.setConfirmTime(LocalDateTime.now());

        if (orderService.updateWithOptimisticLocker(order) == 0) {
            logger.info("商场管理->订单管理->订单提货确认失败:{}", "更新数据已失效");
            throw new RuntimeException("更新数据已失效");
        }

        logger.info("【请求结束】商场管理->订单管理->管理员提货确认,响应结果:{}", "成功!");
        return ResponseUtil.ok();
    }

    /**
     * 根据订单id获取子退货订单
     *
     * @param id
     * @return
     */
    public Object detailRefundOrder(Integer id) {
        DtsOrder order = orderService.findById(id);

        //获取每个退货子订单及每个子订单中的商品信息
        List<RefundOrderVo> refundOrderList = new ArrayList<RefundOrderVo>();
        List<DtsRefundTrace> refundTraceList = refundService.findRefundTraceByOrderId(id);
        for (DtsRefundTrace refundTrace : refundTraceList) {
            RefundOrderVo refundOrder = new RefundOrderVo();
            List<DtsOrderGoods> refundGoodsList = refundService.queryOrderGoodsByRefundId(refundTrace.getId());
            refundOrder.setRefundTrace(refundTrace);
            refundOrder.setRefundGoods(refundGoodsList);
            refundOrderList.add(refundOrder);
        }
        boolean bool = false;
        if(adminDataAuthService.isAdminManager()){
            bool = true;
        }
        UserVo user = userService.findUserVoById(order.getUserId());
        Map<String, Object> data = new HashMap<>();
        data.put("order", order);
        data.put("isRoot", bool);
        data.put("refundOrderList", refundOrderList);
        data.put("user", user);

        logger.info("【请求结束】商场管理->订单管理->子退货订单详情,响应结果:{}", JSONObject.toJSONString(data));
        return ResponseUtil.ok(data);
    }


    public Object verifyAccounting(String startTime, String endTime, Integer brandId) {
        Map<String, Object> data = new HashMap<>();
        data.put("items", orderService.verifyAccounting(startTime, endTime, brandId));
        return ResponseUtil.ok(data);
    }

}
